import React, { useEffect, useState , useCallback, useMemo,lazy, Suspense} from 'react';
import 'bootstrap/dist/css/bootstrap.css';
import {BrowserRouter,Routes,Route} from 'react-router-dom'
import { ToastContainer } from 'react-toastify';
import 'react-toastify/dist/ReactToastify.css';
import {Login,Register,Profile} from './pages/user';
import constants from './constants';
import eventEmitter from './utils/EventEmitter';
import { Container, Dropdown, DropdownItem, DropdownMenu } from 'react-bootstrap';
import {useTranslation} from 'react-i18next';
import { SupportLanguages } from './services/i18n';
import { UserHelper } from './helper';
import './services/i18n';
import "./App.css"
import AuthenticationContext from './context/Context';

import Home from './pages/home';
import HomeNavBar from './components/navbar/HomeNavBar';
import Guide from './pages/ai/model/guide';
import Analyze from './pages/ai/model/analyze';
import Train from './pages/ai/model/train';
import Dump from './pages/ai/model/dump';

const ChatHome = lazy(()=>import("./pages/chat"))
const ChatChannel = lazy(()=>import("./pages/chat/channel"))
const ChatGroup = lazy(()=>import("./pages/chat/group"))
const ChatConversation = lazy(()=>import("./pages/chat/conversation"))
const ChatContact = lazy(()=>import("./pages/chat/contact"))
const EditContact = lazy(()=>import("./pages/chat/contact/edit"))
const ChatBot = lazy(()=>import("./pages/chat/bot"))
const ChatDialog = lazy(()=>import("./pages/chat/chatdialog"))
const AddOrEditChatGroup = lazy(()=>import("./pages/chat/group/edit"))
const Mall = lazy(()=>import("./pages/mall"))
const Cart = lazy(()=>import("./pages/mall/cart"))
const MallSettings = lazy(()=>import("./pages/mall/setting"))
const ProductList = lazy(()=>import("./pages/mall/product"))
const ProductDetail = lazy(()=>import("./pages/mall/product/detail"))
const Blog = lazy(()=>import("./pages/blog"))
const Articles = lazy(()=>import('./pages/blog/articles/index'));
const PostEditor = lazy(()=>import('./pages/blog/editor/index'));
const SiteMaintance = lazy(()=>import('./pages/sitemaintain'))
const LegalInfo = lazy(()=>import('./pages/sitemaintain/legal'));
const GraphQLPlayground = lazy(()=>import('./pages/graphql')) ;
const MyAITasks = lazy(()=>import('./pages/ai/models/MyTasks')) 
const AIHome = lazy(()=>import('./pages/ai'));
const AITaskBuild = lazy(()=>import('./pages/ai/model'))  
const About = lazy(()=>import('./pages/aboutus'));
const Settings = lazy(()=>import('./pages/settings'));
const Statics = lazy(()=>import('./pages/settings/statics'));
const NoPage = lazy(()=>import('./pages/error/nopage'));
const FileManager = lazy(()=>import('./pages/settings/file'));
const FileDetail = lazy(()=>import('./pages/settings/file/detail'));
const Tools = lazy(()=>import("./pages/tools"));

//TODO: i18n
function App(props:any) {

  const [ui,setui] = useState(UserHelper.getCachedUserInfo());
  const [hidetop,setHideTop] = useState(false);
  const [navBgColor,setNavBgColor] = useState("rgba(0,0,0,0)");
  const {i18n} = useTranslation();

  //全局监听
  eventEmitter.subscribe(constants.str.hideTopContent,(data:any)=>{
    setHideTop(true)
  })
  eventEmitter.subscribe(constants.str.network.err401,(data:any)=>{
    document.location.replace("/user/login")
  })

  const setupLanguage = ()=> {
    const language = navigator.language;
    console.debug(`detected current language ${language}`)
    i18n.changeLanguage(language||"en");
  }

  useEffect(()=>{
    const scrollListener = ()=>{
      if(window.scrollY > 0 && window.scrollY<=150){
        const alpha = window.scrollY/110.0;
        console.debug("alpha:"+alpha);
        setNavBgColor(`rgba(255,255,255,${alpha})`);
      }
    };
    setupLanguage();
    window.addEventListener("scroll",scrollListener);
    return ()=> {
      window.removeEventListener("scroll",scrollListener);
    }
    //todo destruct
  },[props,ui,hidetop])

  const afterLogin = useCallback(()=>{
    setui(UserHelper.getCachedUserInfo());
    setHideTop(false);
  },[])

  const contextValue = useMemo(()=>{
    return {userInfo:ui,afterLogin}
  },[ui,afterLogin]);

  const selectLanguage = (eventKey:string|null, e: React.SyntheticEvent<unknown>)=>{
    e.preventDefault();
    e.stopPropagation();
    i18n.changeLanguage(eventKey||"en");
  }

  const renderLanguageControl = ()=> {
    return (<Dropdown
    style={{zIndex:1039}}
      onSelect={selectLanguage}
    >
      <Dropdown.Toggle variant='none'>
      {i18n.language}
      </Dropdown.Toggle>
      <DropdownMenu>
      {SupportLanguages.map((lng,idx)=>{
        return (<DropdownItem key={`lng-${idx}`} eventKey={lng}>{lng}</DropdownItem>)
      })}
    </DropdownMenu>
    </Dropdown>)
  }

  return (<AuthenticationContext.Provider value={contextValue}>
      <Container id="basecontainer" fluid className='d-flex flex-column p-0 m-0 baseContainer'>
              <Container fluid className='d-flex flex-row justify-content-between p-0 m-2' style={{width:"100%"}}>
                {renderLanguageControl()} 
                <Container className='d-flex flex-row justify-content-end p-0 m-0'>
                  {hidetop ? null :(ui.username && ui.username.length > 0 ? (<p className='text-end pe-3'><a href='/user/profile'>Hello,{ui.username}</a>&nbsp;<button onClick={(e)=>{
                  e.preventDefault();
                  UserHelper.removeCachedUserInfo(ui.username);
                  setui({})
                  eventEmitter.dispatch(constants.str.network.err401);
            }}>Logout</button></p>) :<p className='text-end pe-3'><button onClick={(e)=>{
              e.preventDefault();
              eventEmitter.dispatch(constants.str.network.err401);
            }}>Login</button></p>)}</Container></Container>
              
          {!hidetop && <HomeNavBar bgColor={navBgColor}/>}
          <Suspense fallback={<div>Loading...</div>}>
            <BrowserRouter>      
            <Routes>
                <Route index path='/' element={<Home />} />
                <Route path="settings" element={<Settings/>}>
                  {/* <Route path='settings' element={}/> */}
                </Route>
                <Route path='dashboard' element={<Statics/>}/>
                <Route path="blog" element={<Blog />} >
                  <Route index element={<Articles/>}></Route>
                  <Route path='articles' element={<Articles/>}/>
                </Route>
                <Route path='blog/editor' element={<PostEditor/>}/>
                <Route path="chat" element={<ChatHome/>} >
                  <Route index element={<ChatConversation/>}/>
                  <Route path='conversations' element={<ChatConversation/>}/>
                  <Route path='contact' element={<ChatContact/>}/>
                  <Route path='group' element={<ChatGroup/>}/>
                  <Route path='channel' element={<ChatChannel/>}/>
                  <Route path='bot' element={<ChatBot/>}/>
                  <Route path='notification' element={<ChatBot/>}/>
                </Route>
                <Route path="chat/contact/edit" element={<EditContact/>} />
                <Route path='chat/addgroup' element={<AddOrEditChatGroup/>}/>
                <Route path="contactus" element={<ChatBot/>} />
                <Route path="chat/dialog" element={<ChatDialog/>} />
                <Route path="mall" element={<Mall/>} />
                <Route path="mall/cart" element={<Cart/>} />
                <Route path="mall/product/list" element={<ProductList/>} />
                <Route path="mall/product/detail" element={<ProductDetail/>} />
                <Route path="mall/settings" element={<MallSettings/>} />
                <Route path="mall/chat" element={<ChatConversation/>}/>
                <Route path='user/login' element={<Login/>}></Route>
                <Route path='user/register' element={<Register/>}></Route>
                <Route path='user/profile' element={<Profile/>}></Route>
                <Route path="aboutus" element={<About />} />
                <Route path="document" element={<FileManager />} />
                <Route path="document/detail" element={<FileDetail />} />
                <Route path='tools' element={<Tools/>}></Route>
                <Route path='site' element={<SiteMaintance/>}/>
                <Route path='site/legal' element={<LegalInfo/>}/>
                <Route path='graphqlpg' element={<GraphQLPlayground/>}/>
                <Route path='inference' element={<AIHome/>}>
                  <Route index element={<MyAITasks/>}></Route>
                  <Route path='guide' element={<Guide/>}></Route>
                  <Route path='build' element={<AITaskBuild/>}>
                    <Route index element={<Analyze/>}></Route>
                    <Route path='train' element={<Train/>}></Route>
                    <Route path='dump' element={<Dump/>}></Route>
                  </Route>
                </Route>
                <Route path="*" element={<NoPage />} />
            </Routes>
            </BrowserRouter>
          </Suspense>
          <ToastContainer/>
        </Container>
    </AuthenticationContext.Provider>);
}

export default App;
